package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * ClassName: StringToBaseEnumConverterFactory
 * Descripition: 实现String 到 BaseEnum每个子类的转换
 *
 * @Create: 2024/12/10 - 下午 10:30
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String code) {
                // 得到枚举类的全部实例，等同于
                T[] enumConstants = targetType.getEnumConstants();
                for (T enumConstant : enumConstants) {
                    //因为枚举类的值是数字，所以需要把code转换为Integer类型
                    if(enumConstant.getCode().equals(Integer.valueOf(code))){
                        return enumConstant;
                    }
                }
                throw new IllegalArgumentException("code: " + code + "非法");
            }
        };
    }
}
